﻿using API.Common;
using API.Constant;
using API.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace API.Controllers.Api
{
    public class UserController : ApiController
    {
        private DataLinqDataContext db = new DataLinqDataContext();
        private Dictionary<string, object> ResponseStatus = new Dictionary<string, object>();
        private Dictionary<string, object> returnData = new Dictionary<string, object>();
        private ReturnStatusConstant returnStatus;
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAllUser")]
        public HttpResponseMessage GetAllUser()
        {
            try
            {
                var checkHeader = APICommon.CheckEtoken(Request.Headers);
                if (checkHeader)
                {
                    var getAllUser = (from m in db.tbl_users
                                      select new User
                                      {
                                          Username = m.Username,
                                          Zipcode = m.Zipcode,
                                          Address = m.Address,
                                          Avatar = m.Avatar,
                                          Birthday = m.Birthday,
                                          Email = m.Email,
                                          FacebookID = m.FacebookID,
                                          FaceName = m.FaceName,
                                          FullName = m.FullName,
                                          Gender = m.Gender,
                                          Locations = new Location() { Id = m.IdCountry, Country = db.tb_Locations.FirstOrDefault(t => t.Id == m.IdCountry).Country },
                                          Scores = (from u in db.tb_Scores
                                                    where u.Username == m.Username
                                                    select new Score
                                                    {
                                                        IdLesson = u.IdLesson,
                                                    }).ToList()
                                      }).ToList();

                    returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeNone, Status.Success, MessageResponse.MessageNone, APICommon.Etoken);
                    returnData.Add("status", returnStatus);
                    returnData.Add("returnUser", getAllUser);
                    return Request.CreateResponse(HttpStatusCode.Created, returnData);
                }
                else
                {
                    returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeInvalidUserName, Status.Faiure, MessageResponse.MessageInvalidEtoken, string.Empty);
                    returnData.Add("status", returnStatus);
                    return Request.CreateResponse(HttpStatusCode.Created, returnData);
                }
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        /// <summary>
        /// GetUserInfo
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetUserInfo")]
        public HttpResponseMessage GetUserInfo()
        {
            if (APICommon.CheckEtoken(Request.Headers))
            {
                tbl_user tbl_user = db.tbl_users.First(t => t.Username == APICommon.UserName);

                if (tbl_user != null)
                {
                    returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeNone, Status.Success, MessageResponse.MessageNone, APICommon.Etoken);
                    returnData.Add("status", returnStatus);
                    returnData.Add("returnUser", new User()
                    {
                        Username = tbl_user.Username,
                        Zipcode = tbl_user.Zipcode,
                        Address = tbl_user.Address,
                        Avatar = tbl_user.Avatar,
                        Birthday = tbl_user.Birthday,
                        Email = tbl_user.Email,
                        FacebookID = tbl_user.FacebookID,
                        FaceName = tbl_user.FaceName,
                        FullName = tbl_user.FullName,
                        Gender = tbl_user.Gender,
                        Locations = new Location() { Id = tbl_user.IdCountry, Country = db.tb_Locations.FirstOrDefault(t => t.Id == tbl_user.IdCountry).Country },
                        Scores = (from u in db.tb_Scores
                                  where u.Username == tbl_user.Username
                                  select new Score
                                  {
                                      IdLesson = u.IdLesson,
                                  }).ToList()
                    });
                    return Request.CreateResponse(HttpStatusCode.Created, returnData);
                }
                else
                {
                    returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeInvalidUserName, Status.Faiure, MessageResponse.MessageInvalidEtoken, string.Empty);
                    returnData.Add("status", returnStatus);
                    return Request.CreateResponse(HttpStatusCode.Created, returnData);
                }
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        [HttpPost]
        [ActionName("SignUp")]
        public HttpResponseMessage SignUp(User user)
        {
            HttpResponseMessage response;
            if (ModelState.IsValid)
            {
                var checkUser = db.tbl_users.FirstOrDefault(t => t.Username == user.Username);
                if (checkUser == null)
                {
                    db.tbl_users.InsertOnSubmit(new tbl_user()
                    {
                        Username = user.Username,
                        Zipcode = user.Zipcode,
                        Address = user.Address,
                        Avatar = user.Avatar,
                        Birthday = user.Birthday,
                        Email = user.Email,
                        FacebookID = user.FacebookID,
                        FaceName = user.FaceName,
                        FullName = user.FullName,
                        Gender = user.Gender,
                        IdCountry = (int)user.IdCountry,
                        Password = user.Password
                    });
                    try
                    {
                        db.SubmitChanges();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
                    }
                    var upDateEtoken = db.VerifyUserlogin(user.Username, user.Password).ToString();
                    if (upDateEtoken == "0")
                    {
                        var getAllUser = (from m in db.tbl_users
                                          where m.Username == user.Username
                                          select new User
                                          {
                                              Username = m.Username,
                                              Zipcode = m.Zipcode,
                                              Address = m.Address,
                                              Avatar = m.Avatar,
                                              Birthday = m.Birthday,
                                              Email = m.Email,
                                              FacebookID = m.FacebookID,
                                              FaceName = m.FaceName,
                                              FullName = m.FullName,
                                              Gender = m.Gender,
                                              Etoken = m.Etoken,
                                              Locations = new Location() { Id = m.IdCountry, Country = db.tb_Locations.FirstOrDefault(t => t.Id == m.IdCountry).Country },
                                              Scores = (from u in db.tb_Scores
                                                        where u.Username == m.Username
                                                        select new Score
                                                        {
                                                            IdLesson = u.IdLesson,
                                                        }).ToList()
                                          }).First();

                        returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeNone, Status.Success, MessageResponse.MessageNone, getAllUser.Etoken);
                        returnData.Add("status", returnStatus);
                        returnData.Add("returnUser", getAllUser);
                        return Request.CreateResponse(HttpStatusCode.Created, returnData);
                    }


                }
                else
                {

                    returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeDataExisted, Status.Faiure, MessageResponse.MessageDataExisted, string.Empty);
                    returnData.Add("status", returnStatus);
                    response = Request.CreateResponse(HttpStatusCode.Created, returnData);
                    response.Headers.Location = new Uri(Url.Link("ApiLogin", new { id = user.Username }));
                    return response;
                }
                return null;

            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

        }
        //POST api/User
        [HttpPost]
        [ActionName("Login")]
        public HttpResponseMessage Login(User user)
        {
            if (ModelState.IsValid)
            {
                if (user!=null && !string.IsNullOrEmpty(user.Username))
                {
                    var upDateEtoken = db.VerifyUserlogin(user.Username.Trim(), user.Password.Trim()).ToString();
                    if (upDateEtoken == "0")
                    {
                        var getUser = (from m in db.tbl_users
                                       where m.Username == user.Username
                                       select m).FirstOrDefault();

                        if (getUser != null)
                        {

                            var selectData = (from d in db.tbl_users
                                              where d.Username.ToLower() == user.Username.ToLower()
                                              select d).First();

                            returnData.Add("status", new ReturnStatusConstant(ErrorCode.ErrorCodeNone, Status.Success, MessageResponse.MessageNone, selectData.Etoken));
                            returnData.Add("returnUser", new User()
                            {
                                Username = selectData.Username,
                                Zipcode = selectData.Zipcode,
                                Address = selectData.Address,
                                Avatar = selectData.Avatar,
                                Birthday = selectData.Birthday,
                                Email = selectData.Email,
                                FacebookID = selectData.FacebookID,
                                FaceName = selectData.FaceName,
                                FullName = selectData.FullName,
                                Gender = selectData.Gender,
                                Locations = new Location() { Id = selectData.IdCountry, Country = db.tb_Locations.FirstOrDefault(t => t.Id == selectData.IdCountry).Country },
                                Scores = (from u in db.tb_Scores
                                          where u.Username == selectData.Username
                                          select new Score
                                          {
                                              IdLesson = u.IdLesson,
                                          }).ToList()
                            });
                            return Request.CreateResponse(HttpStatusCode.Created, returnData);
                        }
                        else
                        {
                            returnStatus = new ReturnStatusConstant(ErrorCode.ErrorCodeInvalidUserName, Status.Faiure, MessageResponse.MessageInvalidUser, string.Empty);
                            returnData.Add("status", returnStatus);
                            return Request.CreateResponse(HttpStatusCode.Created, returnData);

                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.NotFound, new ReturnStatusConstant(ErrorCode.ErrorCodeInvalidUserName, Status.Faiure, MessageResponse.MessageInvalidUser, string.Empty));
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound, new ReturnStatusConstant(ErrorCode.ErrorCodeInvalidUserName, Status.Faiure, MessageResponse.MessageInvalidUser, string.Empty));
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new ReturnStatusConstant(ErrorCode.ErrorCodeInvalidUserName, Status.Faiure, MessageResponse.MessageInvalidUser, string.Empty));
            }
        }
    }
}
